package com.sgb.merchant.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.reflect.TypeToken;

import com.sgb.link.router.PathMerchant;
import com.sgb.link.utils.GsonManager;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityPublishSelectCityBinding;
import com.sgb.merchant.viewmodel.SelectCityModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DisplayUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.TwoLevelMultiAreaWindow;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 王彬臣
 * @date: 2021/9/16
 * @Description: 发布投资需求-城市要求
 */
@Route(path = PathMerchant.SelectCityActivity)
public class SelectCityActivity extends BaseActivity<SelectCityModel, MerchantActivityPublishSelectCityBinding> {

    private TwoLevelMultiAreaWindow mCityPop;//筛选城市窗口
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> mCityDatas;//城市数据
    private List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>> allList;


    private TagAdapter cityAdapter;
    private TagAdapter cityDeleteAdapter;
    private TagFlowLayout flowLayout;
    private ArrayList<BaseAreaEntity> choosenCityList;

    @Autowired(name = RouterKey.DATA)
    public ArrayList<BaseAreaEntity> list;



    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_publish_select_city;
    }

    @Override
    protected void createViewModel() {
        mViewModel=new ViewModelProvider(this).get(SelectCityModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.actionBar.setOnBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBinding.tvAdd.setOnClickListener(this);
        mBinding.ivDelete.setOnClickListener(this);
        mBinding.tvDeleteAll.setOnClickListener(this);
        mBinding.tvComplete.setOnClickListener(this);
        mBinding.tvConfirm.setOnClickListener(this);
        flowLayout = mBinding.getRoot().findViewById(R.id.city_list);
        initWindow();
        initData();
        mViewModel.ldServiceCity.observe(this, this::showCityPopWindow);
    }

    private void initData() {
        if ((ArrayList<BaseAreaEntity>) getIntent().getSerializableExtra(RouterKey.DATA) != null) {
            choosenCityList = (ArrayList<BaseAreaEntity>) getIntent().getSerializableExtra(RouterKey.DATA);
        } else {
            choosenCityList = new ArrayList<>();
        }
        if (choosenCityList != null && choosenCityList.size() == 20) {
            mBinding.tvAdd.setVisibility(View.GONE);
        }
        if (choosenCityList != null && choosenCityList.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
        }
        cityAdapter = new TagAdapter<BaseAreaEntity>(choosenCityList) {
            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, BaseAreaEntity entity) {
                final LayoutInflater mInflater = LayoutInflater.from(SelectCityActivity.this);
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.merchant_item_service_city, flowLayout, false);
                TextView tv = layout.findViewById(R.id.tv_info);
                tv.setText(entity.getName());
                return layout;
            }
        };
        flowLayout.setAdapter(cityAdapter);
        cityAdapter.notifyDataChanged();
    }

    private void initWindow() {
        mCityPop = new TwoLevelMultiAreaWindow(this);
        mCityPop.setMemberHeight();
        mCityPop.setShowSimpleName(true);
        mCityPop.setOnlyShowProAndCity(true);
        mCityPop.setThreeListIsGone(true);
        mCityPop.setProvinceMore();
        mCityPop.setCityMore();
        mCityPop.setOnResultClick(new BasePopWindow.OnResultClick() {
            @SuppressLint("ResourceType")
            @Override
            public void result(Object key1, Object key2, Object key3) {
                allList = (List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>>) key3;
                flowLayout.setVisibility(View.VISIBLE);
                mBinding.ivDelete.setVisibility(View.VISIBLE);
                mBinding.llDelete.setVisibility(View.GONE);
                if (choosenCityList != null) {
                    choosenCityList.clear();
                    choosenCityList.addAll((ArrayList<BaseAreaEntity>) key1);
                    if (choosenCityList != null && choosenCityList.size() == 20) {
                        mBinding.tvAdd.setVisibility(View.GONE);
                    }
                    cityAdapter = new TagAdapter<BaseAreaEntity>(choosenCityList) {
                        @Override
                        public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, BaseAreaEntity entity) {
                            final LayoutInflater mInflater = LayoutInflater.from(SelectCityActivity.this);
                            LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.merchant_item_service_city, flowLayout, false);
                            TextView tv = layout.findViewById(R.id.tv_info);
                            tv.setText(entity.getName());
                            return layout;
                        }
                    };
                    flowLayout.setAdapter(cityAdapter);
                    cityAdapter.notifyDataChanged();
                    flowLayout.setOnTagClickListener(null);
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_add) {
            if (!ClickUtils.isDoubleClick()) {
                if (mCityDatas == null) {
                    mViewModel.getServiceCity();
                } else if (allList != null && allList.size() > 0) {
                    mCityPop.BaseData(allList, false);
                    mCityPop.showPopwindowBottom(mBinding.tvConfirm);
                } else if (mCityDatas != null && mCityDatas.size() > 0 && choosenCityList != null && choosenCityList.size() > 0) {
                    showCityPopWindow(mCityDatas);
                } else {
                    mCityPop.showPopwindowBottom(mBinding.tvConfirm);
                }
            }
        } else if (id == R.id.iv_delete) {//删除
            if (!ClickUtils.isDoubleClick()) {
                mBinding.ivDelete.setVisibility(View.GONE);
                mBinding.llDelete.setVisibility(View.VISIBLE);
                cityDeleteAdapter = new TagAdapter<BaseAreaEntity>(choosenCityList) {
                    @Override
                    public View getView(FlowLayout parent, int position, BaseAreaEntity entity) {
                        final LayoutInflater mInflater = LayoutInflater.from(SelectCityActivity.this);
                        LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.merchant_item_delete_service_city, flowLayout, false);
                        TextView tv = layout.findViewById(R.id.tv_info);
                        tv.setText(entity.getName());
                        return layout;
                    }
                };
                flowLayout.setAdapter(cityDeleteAdapter);
                flowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                    @Override
                    public boolean onTagClick(View view, int position, FlowLayout parent) {
                        if (mBinding.tvAdd.getVisibility() == View.GONE) {
                            mBinding.tvAdd.setVisibility(View.VISIBLE);
                        }
                        String name = choosenCityList.get(position).getName();

                        if (allList != null && allList.size() > 0) {
                            if (name.equals("全国")) {
                                for (int i = 0; i < allList.size(); i++) {
                                    allList.get(i).setSelected(false);
                                    for (int j = 0; j < allList.get(i).getChildren().size(); j++) {
                                        allList.get(i).getChildren().get(j).setSelected(false);
                                    }
                                }
                                allList.get(0).setSelected(true);
                            } else {
                                for (int i = 0; i < allList.size(); i++) {
                                    if (allList.get(i).getName().equals(name)) {
                                        allList.get(i).setSelected(false);
                                        for (int a = 0; a < allList.get(i).getChildren().size(); a++) {
                                            allList.get(i).getChildren().get(a).setSelected(false);
                                        }
                                        break;
                                    }
                                    for (int j = 0; j < allList.get(i).getChildren().size(); j++) {
                                        if (allList.get(i).getChildren().get(j).getName().equals(name)) {
                                            allList.get(i).getChildren().get(j).setSelected(false);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        choosenCityList.remove(position);
                        cityDeleteAdapter.notifyDataChanged();
                        if (choosenCityList.size() == 0) {
                            flowLayout.setVisibility(View.GONE);
                        }
                        return true;
                    }
                });
            }
        } else if (id == R.id.tv_delete_all) {//全部删除
            if (!ClickUtils.isDoubleClick()) {
                if (choosenCityList != null)
                    choosenCityList.clear();
                if (mBinding.tvAdd.getVisibility() == View.GONE) {
                    mBinding.tvAdd.setVisibility(View.VISIBLE);
                }
                flowLayout.setVisibility(View.GONE);
                cityDeleteAdapter.notifyDataChanged();
                mBinding.ivDelete.setVisibility(View.VISIBLE);
                mBinding.llDelete.setVisibility(View.GONE);

                if (allList != null && allList.size() > 0) {
                    for (int i = 0; i < allList.size(); i++) {
                        allList.get(i).setSelected(false);
                        for (int j = 0; j < allList.get(i).getChildren().size(); j++) {
                            allList.get(i).getChildren().get(j).setSelected(false);
                        }
                    }
                    allList.get(0).setSelected(true);
                }
            }
        } else if (id == R.id.tv_complete) {//完成
            if (!ClickUtils.isDoubleClick()) {
                mBinding.ivDelete.setVisibility(View.VISIBLE);
                mBinding.llDelete.setVisibility(View.GONE);
                cityAdapter = new TagAdapter<BaseAreaEntity>(choosenCityList) {
                    @Override
                    public View getView(FlowLayout parent, int position, BaseAreaEntity entity) {
                        final LayoutInflater mInflater = LayoutInflater.from(SelectCityActivity.this);
                        LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.merchant_item_service_city, flowLayout, false);
                        TextView tv = layout.findViewById(R.id.tv_info);
                        tv.setText(entity.getName());
                        return layout;
                    }
                };
                flowLayout.setAdapter(cityAdapter);
                flowLayout.setOnTagClickListener(null);
            }
        } else if (id == R.id.tv_confirm) {
            if (!ClickUtils.isDoubleClick()) {
                if (choosenCityList != null && choosenCityList.size() > 0) {
                    ArrayList<BaseAreaEntity> cityListShow = new ArrayList<>();
                    if (choosenCityList.size() > 1 &&
                            DisplayUtil.px2dip(this, flowLayout.getChildAt(0).getMeasuredWidth() + flowLayout.getChildAt(1).getMeasuredWidth()) > 250) {
                        cityListShow.add(choosenCityList.get(0));
                    }
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cityList", (Serializable) choosenCityList);
                    bundle.putSerializable("cityListShow", (Serializable) cityListShow);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    MToast.showToast(this, "请添加城市");
                }
            }
        }
    }

    public void showCityPopWindow(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> cityDatas) {
        this.mCityDatas = cityDatas;
        if (choosenCityList != null && choosenCityList.size() > 0) {
            String cityListsStr = GsonManager.getInstance().getGson().toJson(cityDatas);
            List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>> list = GsonManager.getInstance().getGson().fromJson(cityListsStr, new TypeToken<List<BaseAreaEntity<List<BaseAreaEntity<List<BaseAreaEntity>>>>>>() {
            }.getType());
            BaseAreaEntity provinceEntity = new BaseAreaEntity();
            provinceEntity.setName("全国");
            provinceEntity.setNo("");
            provinceEntity.setSimpleName("全国");
            provinceEntity.setChildren(new ArrayList<>());
            BaseAreaEntity provinceEntity1 = new BaseAreaEntity();
            provinceEntity1.setName("全国");
            provinceEntity1.setNo("");
            provinceEntity1.setSimpleName("全国");
            provinceEntity1.setSelected(false);
            provinceEntity1.setChildren(new ArrayList<>());
            list.add(0, provinceEntity);
            for (int i = 0; i < list.size(); i++) {
                if (i != 0) {
                    BaseAreaEntity cityEntity = new BaseAreaEntity();
                    cityEntity.setName("全省");
                    cityEntity.setNo("");
                    cityEntity.setSimpleName("全省");
                    cityEntity.setSelected(false);
                    list.get(i).getChildren().add(0, cityEntity);

                    for (int j = 1; j < list.get(i).getChildren().size(); j++) {
                        BaseAreaEntity areaEntity = new BaseAreaEntity();
                        areaEntity.setName("全市");
                        areaEntity.setNo("");
                        areaEntity.setSimpleName("全市");
                        areaEntity.setSelected(false);
                        list.get(i).getChildren().get(j).getChildren().add(0, areaEntity);
                    }
                } else {
                    list.get(i).getChildren().add(0, provinceEntity1);
                }
            }
            String name = "";
            for (int k = 0; k < choosenCityList.size(); k++) {
                name = choosenCityList.get(k).getName();
                if (list != null && list.size() > 0) {
                    if (name.equals("全国")) {
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).setSelected(true);
                            for (int j = 0; j < list.get(i).getChildren().size(); j++) {
                                list.get(i).getChildren().get(j).setSelected(true);
                            }
                        }
                    } else {
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(name)) {
                                list.get(i).setSelected(true);
                                for (int a = 0; a < list.get(i).getChildren().size(); a++) {
                                    list.get(i).getChildren().get(a).setSelected(true);
                                }
                            } else {
                                for (int j = 0; j < list.get(i).getChildren().size(); j++) {
                                    if (list.get(i).getChildren().get(j).getName().equals(name)) {
                                        list.get(i).getChildren().get(j).setSelected(true);
                                        list.get(i).setSelected(true);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            mCityPop.BaseData(list, false);
            mCityPop.showPopwindowBottom(mBinding.tvConfirm);
        } else {
            mCityPop.setMultiData(cityDatas, true);
            mCityPop.showPopwindowBottom(mBinding.tvConfirm);
        }
    }
}
